/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.app.mockexam.theory.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.app.examinate.extheory.user.entity.AppUserExtheory;
import com.jeesite.modules.app.examinate.extheory.user.service.AppUserExtheoryService;
import com.jeesite.modules.app.mockexam.theory.entity.AppExaminateTheory;
import com.jeesite.modules.app.mockexam.theory.service.AppExaminateTheoryService;
import com.jeesite.modules.app.mockexam.theory.user.entity.TmockexamTheoryUser;
import com.jeesite.modules.app.mockexam.theory.user.service.TmockexamTheoryUserService;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;

/**
 * 理论考试对象表Controller
 * @author zpp
 * @version 2020-02-08
 */
@Controller
@RequestMapping(value = "/app/examinate/theory/")
public class AppExaminateTheoryController{

	@Autowired
	private AppExaminateTheoryService appExaminateTheoryService;
	@Autowired
	private AppUserExtheoryService appUserExtheoryService;
	@Autowired
	private TmockexamTheoryUserService tmockexamTheoryUserService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public AppExaminateTheory get(String id, boolean isNewRecord) {
		return appExaminateTheoryService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:view")
	@RequestMapping(value = {"list", ""})
	public String list(AppExaminateTheory appExaminateTheory, Model model) {
		model.addAttribute("appExaminateTheory", appExaminateTheory);
		return "modules/app/examinate/theory/appExaminateTheoryList";
	}
	@RequestMapping(value = "findPage")
	public void findPage(AppExaminateTheory entity, Model model,HttpServletRequest request,HttpServletResponse response) {		
		model.addAttribute("appExaminateTheory", entity);
		entity.setPage(new Page<>(request, response));
		entity.setParentCode("0");
		Page<AppExaminateTheory> findPage = appExaminateTheoryService.findPage(entity);
		List<AppExaminateTheory> list = findPage.getList();
		String userId = request.getParameter("userId");
		if(StringUtils.isNotBlank(userId)){
			for(AppExaminateTheory record:list){
				TmockexamTheoryUser aue=new TmockexamTheoryUser();
				aue.setTheoryId(record.getId());
				aue.setUserId(userId);				
				List<TmockexamTheoryUser> findList = tmockexamTheoryUserService.findList(aue);
				if(findList!=null&&findList.size()>0){
					aue = findList.get(0);
					record.setTypestatus(aue.getType());
				}else{
					record.setTypestatus(0);
				}
			}
		}
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<AppExaminateTheory> listData(AppExaminateTheory appExaminateTheory) {
		if (StringUtils.isBlank(appExaminateTheory.getParentCode())) {
			appExaminateTheory.setParentCode(AppExaminateTheory.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(appExaminateTheory.getObjName())){
			appExaminateTheory.setParentCode(null);
		}
		if (appExaminateTheory.getObjType() != null){
			appExaminateTheory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(appExaminateTheory.getRemarks())){
			appExaminateTheory.setParentCode(null);
		}
		if (appExaminateTheory.getObjExplain() != null){
			appExaminateTheory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(appExaminateTheory.getObjAnswer())){
			appExaminateTheory.setParentCode(null);
		}
		if (StringUtils.isNotBlank(appExaminateTheory.getIntroduction())){
			appExaminateTheory.setParentCode(null);
		}
		List<AppExaminateTheory> list = appExaminateTheoryService.findList(appExaminateTheory);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:view")
	@RequestMapping(value = "form")
	public String form(AppExaminateTheory appExaminateTheory, Model model) {
		// 创建并初始化下一个节点信息
		appExaminateTheory = createNextNode(appExaminateTheory);
		model.addAttribute("appExaminateTheory", appExaminateTheory);
		return "modules/app/examinate/theory/appExaminateTheoryForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public AppExaminateTheory createNextNode(AppExaminateTheory appExaminateTheory) {
		if (StringUtils.isNotBlank(appExaminateTheory.getParentCode())){
			appExaminateTheory.setParent(appExaminateTheoryService.get(appExaminateTheory.getParentCode()));
		}
		if (appExaminateTheory.getIsNewRecord()) {
			AppExaminateTheory where = new AppExaminateTheory();
			where.setParentCode(appExaminateTheory.getParentCode());
			AppExaminateTheory last = appExaminateTheoryService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				appExaminateTheory.setTreeSort(last.getTreeSort() + 30);
				appExaminateTheory.setId(IdGen.nextCode(last.getId()));
			}else if (appExaminateTheory.getParent() != null){
				appExaminateTheory.setId(appExaminateTheory.getParent().getId() + "001");
			}
		}
		// 以下设置表单默认数据
		if (appExaminateTheory.getTreeSort() == null){
			appExaminateTheory.setTreeSort(AppExaminateTheory.DEFAULT_TREE_SORT);
		}
		return appExaminateTheory;
	}

	/**
	 * 保存理论考试对象表
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated AppExaminateTheory appExaminateTheory) {
		appExaminateTheoryService.save(appExaminateTheory);
		return "保存理论考试对象表成功！";
	}
	
	/**
	 * 停用理论考试对象表
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(AppExaminateTheory appExaminateTheory) {
		AppExaminateTheory where = new AppExaminateTheory();
		where.setStatus(AppExaminateTheory.STATUS_NORMAL);
		where.setParentCodes("," + appExaminateTheory.getId() + ",");
		long count = appExaminateTheoryService.findCount(where);
		if (count > 0) {
			return "该理论考试对象表包含未停用的子理论考试对象表！";
		}
		appExaminateTheory.setStatus(AppExaminateTheory.STATUS_DISABLE);
		appExaminateTheoryService.updateStatus(appExaminateTheory);
		return "停用理论考试对象表成功";
	}
	
	/**
	 * 启用理论考试对象表
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(AppExaminateTheory appExaminateTheory) {
		appExaminateTheory.setStatus(AppExaminateTheory.STATUS_NORMAL);
		appExaminateTheoryService.updateStatus(appExaminateTheory);
		return "启用理论考试对象表成功";
	}
	
	/**
	 * 删除理论考试对象表
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(AppExaminateTheory appExaminateTheory) {
		appExaminateTheoryService.delete(appExaminateTheory);
		return "删除理论考试对象表成功！";
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		List<AppExaminateTheory> list = appExaminateTheoryService.findList(new AppExaminateTheory());
		for (int i=0; i<list.size(); i++){
			AppExaminateTheory e = list.get(i);
			// 过滤非正常的数据
			if (!AppExaminateTheory.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getId(), e.getObjName()));
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("app:examinate:theory:appExaminateTheory:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(AppExaminateTheory appExaminateTheory){
		if (!UserUtils.getUser().isAdmin()){
			return "操作失败，只有管理员才能进行修复！";
		}
		appExaminateTheoryService.fixTreeData();
		return "数据修复成功";
	}
	
}